<?php
/**
 * Created by PhpStorm.
 * User: insgeek
 * Date: 2017/2/13
 * Time: 10:35
 * 责任链模式
 */
namespace DesignPattern\ChainOfResponsibilityPattern;

abstract class AbstractLogger
{
    public static  $INFO  = 1;
    public static  $DEBUG = 2;
    public static  $ERROR = 3;

    protected $level;

    protected $nextLogger;

    public function setNextLogger(AbstractLogger $nextLogger)
    {
        $this->nextLogger = $nextLogger;
    }

    public function logMessage(int $level, String $message)
    {
        if($this->level <= $level){
            $this->write($message);
        }
        if($this->nextLogger !=null){
            $this->nextLogger->logMessage($level, $message);
        }
    }

    abstract protected function write(string $message);
}

class ConsoleLogger extends AbstractLogger
{
    public function __construct(int $level)
    {
        $this->level = $level;
    }

    protected function write(string $message)
    {
        // TODO: Implement write() method.
        print_r("Standard Console::Logger: " . $message . PHP_EOL);
    }

}
class FileLogger  extends AbstractLogger
{
    public function __construct(int $level)
    {
        $this->level = $level;
    }

    protected function write(string $message)
    {
        // TODO: Implement write() method.
        print_r("File::Logger: " . $message . PHP_EOL);
    }

}
class ErrorLogger  extends AbstractLogger
{
    public function __construct(int $level)
    {
        $this->level = $level;
    }

    protected function write(string $message)
    {
        // TODO: Implement write() method.
        print_r("Error Console::Logger: " . $message . PHP_EOL);
    }


}

class ChainPatternDemo
{
    public static function getChainOfLoggers()
    {
        $errorLogger = new ErrorLogger(AbstractLogger::$ERROR);
        $fileLogger = new FileLogger(AbstractLogger::$DEBUG);
        $consoleLogger = new ConsoleLogger(AbstractLogger::$INFO);

        $errorLogger->setNextLogger($fileLogger);
        $fileLogger->setNextLogger($consoleLogger);

        return $errorLogger;
    }
}

$loggerChain = ChainPatternDemo::getChainOfLoggers();
$loggerChain->logMessage(AbstractLogger::$INFO, "This is an information.");
$loggerChain->logMessage(AbstractLogger::$DEBUG, "This is an debug level information.");
$loggerChain->logMessage(AbstractLogger::$ERROR, "This is an error information.");